package com.wanmait.schedule.interceptor;

import com.wanmait.schedule.entity.Company;
import com.wanmait.schedule.entity.CompanyUser;
import com.wanmait.schedule.entity.Userinfo;
import com.wanmait.schedule.service.CompanyUserService;
import com.wanmait.schedule.service.UserinfoService;
import com.wanmait.schedule.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LeaderJWTInterceptor implements HandlerInterceptor {

    @Resource
    UserinfoService userinfoService;
    @Resource
    CompanyUserService companyUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("----------------老板拦截器---------------------");
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        String token = request.getHeader("token");//获取请求头部的token
        System.out.println("token::"+token);
        if(token==null||token.equals("null")||token.length()==0){
            System.out.println("notoken");
            throw new Exception("NoToken");//没有token直接报错
        }
        //从token中获得签发对象 admin的id
        Integer id = Integer.parseInt(JWTUtils.getAudience(token));//从token中获取 userinfo 的ID
        CompanyUser companyUser = companyUserService.getCompanyUserByUserinfoId(id);//由 userinfo ID  获得 companyUser 对象

        //System.out.println("companyUser::"+companyUser);
        Userinfo userinfo = userinfoService.getById(id); //从token中获得的 UserinfoID 获得 userinfo
        if(userinfo==null){
            throw new Exception("NoFoundUser");
        }
        //验证token
        if(!JWTUtils.verifyToken(token,userinfo.getPassword())){
            throw new Exception("TokenFail");
        }
        /*m没有考虑其他的 例如department 和 company 是因为如果这个用户以不在职，查找这两个对象已经没有意义*/
        request.setAttribute("companyUser",companyUser); //存入 request中 ，后端使用直接获取
        request.setAttribute("userinfo" , userinfo);

 /*       JSONObject jsonObject = new JSONObject();
        jsonObject.put("companyUser",companyUser);
        jsonObject.put("userinfo",userinfo);

//        ObjectMapper objectMapper = new ObjectMapper();
        //String jsonStr = objectMapper.writeValueAsString(Result.success("请先登录"));
        String jsonStr = JSON.toJSONString(jsonObject);
        //Result result = (Result)JSON.parse(jsonStr);
        response.setContentType("text/html;charset=UTF-8");
        //response.setCharacterEncoding("UTF-8");
        response.getWriter().print(jsonStr);*/
        return true;
    }
}
